package com.jar.netty_demo.Netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.net.URI;
import java.nio.charset.Charset;

/**
 * HttpObject  客户端和服务器端相互通讯的数据被封装程HttpObject
 */
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    private static final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if (msg instanceof HttpRequest) {
            System.out.println("msg 类型" + msg.getClass());
            System.out.println("客户端地址：" + ctx.channel().remoteAddress());
            //对特定资源进行过滤
            HttpRequest httpRequest = (HttpRequest) msg;
            String uri = httpRequest.uri();
            if ("/favicon.ico".equals(uri)) {
                System.out.println("浏览器请求了favicon.ico,不做处理");
                return;
            }
            //给浏览器发送信息
            ByteBuf content = Unpooled.copiedBuffer("Hello ,我是服务器", Charset.defaultCharset());
            //构造一个http的响应
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
            ctx.writeAndFlush(response);
            ctx.fireChannelActive();
        }
    }
}
